<<?php
require_once 'Course.php';

class Student
{
    private $surname;
    private $first_name;
    private $emails;
    private $status;
    private $grades; // 改为关联数组，键为课程编号，值为成绩
    private $courses; // 存储课程对象的数组

    public function __construct($surname, $first_name)
    {
        $this->surname = $surname;
        $this->first_name = $first_name;
        $this->emails = array();
        $this->status = '';
        $this->grades = array();
        $this->courses = array();
    }

    public function add_email($which, $address)
    {
        $this->emails[$which] = $address;
    }

    public function set_status($status)
    {
        $this->status = $status;
    }

    // 新增添加课程的方法
    public function add_course(Course $course)
    {
        $this->courses[$course->getCourseCode()] = $course;
    }

    // 修改添加成绩的方法，根据课程编号关联成绩
    public function add_grade($courseCode, $grade)
    {
        $this->grades[$courseCode] = $grade;
    }

    public function average()
    {
        if (empty($this->grades)) {
            return 0;
        }
        $total = array_sum($this->grades);
        return round($total / count($this->grades), 1);
    }

    public function toString()
    {
        $result = "{$this->first_name} {$this->surname} | 平均分：{$this->average()} | 年级：{$this->status}\n";
        
        $result .= "联系方式：\n";
        foreach ($this->emails as $type => $address) {
            $result .= "  - {$type}：{$address}\n";
        }
        
        $result .= "已修课程及成绩：\n";
        foreach ($this->courses as $courseCode => $course) {
            $grade = isset($this->grades[$courseCode]) ? $this->grades[$courseCode] : '无成绩';
            $result .= "  - {$course->toString()}：{$grade}分\n";
        }
        
        return '<pre>' . $result . '</pre>';
    }
}
?>